package com.huc.config.aspect;

import com.alibaba.fastjson.JSONObject;
import com.huc.config.db.DynamicDataSourceContextHolder;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;

/**
 * @Author: 胡成
 * @Version: 0.0.1V
 * @Date: 2019-04-24
 * @Description: 数据源切面
 **/
@Slf4j
@Aspect
@Component
public class DynamicDataSourceAspect {

    @Before("@annotation(ds)")
    public void changeDataSource(JoinPoint point, DataSource ds) throws Throwable {
        String dsId = ds.value();

        Object[] objects = point.getArgs();
        JSONObject jsonObject = JSONObject.parseObject(JSONObject.toJSONString(objects[0]));

        String key = jsonObject.getString(dsId);
        System.out.println(key);
        int i = Math.abs(key.hashCode() % 2);
        System.out.println(i);
//        System.out.println("库节点：" + );
//        System.out.println("表节点：" + Math.abs(l.hashCode() / 2 % 2));
//        objects[0];
//        for(int i = 0;i<objects.length;i++){
//            System.out.println(objects[i]);
//        }

        String databaseName = "m" + (i + 1);

        if (DynamicDataSourceContextHolder.containsDataSource(databaseName)) {
            log.debug("Use DataSource :{} >", databaseName, point.getSignature());
            DynamicDataSourceContextHolder.setDataSourceRouterKey(databaseName);
        } else {
            log.info("数据源[{}]不存在，使用默认数据源 >{}", databaseName, point.getSignature());
        }
    }

    @After("@annotation(ds)")
    public void restoreDataSource(JoinPoint point, DataSource ds) {
        log.debug("Revert DataSource : " + ds.value() + " > " + point.getSignature());
        DynamicDataSourceContextHolder.removeDataSourceRouterKey();
    }
}
